<?php

namespace App\Http\Middleware\Common;

use App\Exceptions\BaseException;
use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\Common\Enum\CodeEnum;
use App\Kuafu\User\Model\Permissions;
use App\Kuafu\User\Model\RolePermissionMappings;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\User\Service\PermissionsService;
use App\Kuafu\User\Service\UserRoleService;
use Closure;
use Illuminate\Http\Request;


class UserPermissionAuth
{
    /**
     * Check Header Id [shopId, brandId]
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param string|null ...$guards
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $userInfo = AuthService::getAuthUser();
        if ($userInfo->status == \App\Kuafu\User\Enum\CodeEnum::USER_STATUS_STOP) {
            throw new BaseException(BaseCodeEnum::ERR_ACCOUNT_BANNED);
        }

        $userId  = AuthService::getUserId();
        $brandId = $request->header('brandId');
        $shopId  = $request->header('shopId');


        $action         = $request->route()->getAction('controller');
        $actionSplit    = explode('Controller\\', $action);
        $controllerList = strtolower(str_replace(['@', '\\', 'Controller'], ['.', '.', ''], $actionSplit[1]));

        // 白名单
        $whiteList = config('routeWhiteList.pos');
        if (in_array($controllerList, $whiteList)) {
            return $next($request);
        }

        // 获取当前用户的角色 ID
        $roleList = UserRoleService::getWebUserRoleList((int)$userId, (int)$brandId, (int)$shopId);

        try {
            // 获取所有的 判断需要校验的名单
            $permissionAll = Permissions::getAll(CodeEnum::PLATFORM_B_BRAND)->pluck('action')->map(function ($value) {
                return strtolower($value);
            })->toArray();

            // 获取角色的所有权限列表
            $rolePermissionIdsAll = RolePermissionMappings::getAllByRoleList($roleList)->pluck('permissionId')
                                                          ->toArray();

            $rolePermissionIdsAll = Permissions::getAllByIds($rolePermissionIdsAll, CodeEnum::PLATFORM_B_BRAND)
                                               ->pluck('action')->map(function ($value) {
                    return strtolower($value);
                })->toArray();

            // 判断当前路由在不在 总路由中, 存在则校验,不存在则跳过
            if (in_array($controllerList, $permissionAll)) {
                if (in_array($controllerList, $rolePermissionIdsAll)) {
                    // 有权限
                    return $next($request);
                } else {
                    // 没权限
                    throw new BaseException(BaseCodeEnum::ERR_NO_ACCESS);
                }
            } else {
                // 跳过校验
                return $next($request);
            }
        } catch (BaseException $exception) {
            throw new BaseException(BaseCodeEnum::ERR_NO_ACCESS);
        }
    }
}
